#include <iostream>
#include <string>
#include "Reactor.hpp"
#include "Listener.hpp"
#include "Channel.hpp"
#include "Log.hpp"
#include "common.hpp"
#include "Protocol.hpp"
#include "NetCal.hpp"
static void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc << " port" << std::endl;
}
int main(int argc,char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    LogMoudle::ConsoleLogStrategy();
    uint16_t port=std::stoi(argv[1]);
    //业务模块
    std::shared_ptr<Cal> q=std::make_shared<Cal>();
    //协议模块
    std::shared_ptr<Protocol> p=std::make_shared<Protocol>([q](Request &req)->Response{
        return q->Execute(req);
    });
    //链接模块
    std::shared_ptr<Connection> s=std::make_shared<Listener>(port);
    s->RegisterHandler([p](std::string& inbuffer)->std::string{
        LOG(loglevel::DEBUG) << "进入到匿名函数中...";
        std::string response_str;
        while(true)
        {
            std::string package;
            if(!p->Decode(inbuffer,&package))
            {
                break;
            }
            response_str+=p->Execute(package);
        }
         LOG(loglevel::DEBUG) << "结束匿名函数中...: " << response_str;
        return response_str; 
    });
    // 构建一个reactor反应器模块
    std::unique_ptr<Reactor> R = std::make_unique<Reactor>();
    R->AddConnection(s);
    R->loop();
    return 0;
}